import os
import pickle
from constants import MAP_HEIGHT, MAP_WIDTH, TILE_SIZE
import xml.etree.cElementTree as ET
#from ships.shipfactory import ShipFactory
import ship
import random
import numpy as np

class Level():
    '''
    Contains methods that are connected to the current map we are playing.
    http://theory.stanford.edu/~amitp/GameProgramming/MapRepresentations.html
    '''
    name = ''
    description = ''
    
    #start_node = None
    #target_node = None
    #navigation_map = None
    #navigation_graph = None
    #build_map = None
    
    no_more_ships = False
    game_time = 0
    ships = list()
    ship_counter = 0
    commandship_position = None
    
    def __init__(self):
        pass
    
    def update(self, time, ship_list):
        if self.no_more_ships:
            return
        
        self.game_time += time
        if self.game_time >= self.ships[self.ship_counter]['time']:
            ship_type = self.ships[self.ship_counter]['name']
            spawnpoint = self.ships[self.ship_counter]['spawnpoint'].split(',')
            pos_x = random.randint( int(spawnpoint[0]), int(spawnpoint[1]) )
            pos_y = random.randint( int(spawnpoint[2]), int(spawnpoint[3]) )
            #ship_list.add( ShipFactory().create_ship(ship_type,[pos_x,pos_y] ) )
            ship_list.add( ship.Ship( ship_type, [pos_x,pos_y]  )  )
            self.ship_counter += 1
            
        if self.ship_counter >= len( self.ships ):
            self.no_more_ships = True
    
    def load_map(self, map_name):
        '''
        Loads all level data for a given level file. The level files are stored
        in a XML structure.
        '''
        map_name = os.path.join('..', 'data', 'levels', map_name)
        map_name = map_name + '.xml'
        
        tree = ET.ElementTree(file=map_name)
            
        self.name = tree.find('name').text
        self.description = tree.find('description').text
        
        cs_pos = tree.find('commandship/position').text
        self.commandship_position = np.fromstring(cs_pos, dtype=np.int, sep=',')
        
        shipgroup = tree.iterfind('ships/shipgroup')
        for ship in shipgroup:
            time = int( ship.find('starttime').text )
            name = ship.find('name').text
            spawnpoint = ship.find('spawnpoint').text
            delay = int( ship.find('delay').text )
            count = int( ship.find('count').text )
            for i in range( count ):
                self.ships.append( {'time' : time+delay*i,  \
                    'name' : name, 'spawnpoint' : spawnpoint}  )

        self.ships.sort(key=lambda x:x['time'] )      
    
    def allow_build(self, x, y):
        '''
        Check if the given coordinates are allowed to build on
        FIXME: Obsolete function, always returns true
        '''
        return True